# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

from coin.base.book import BookBuilderBase
from coin.exchange.fcoin.kr_rest.product import FcoinProduct


class BookEntry(object):
  def __init__(self, price, qty):
    self.price = float(price)
    self.qty = float(qty)


class BookBuilder(BookBuilderBase):
  ProductType = FcoinProduct

  def __init__(self, native_symbol):
    super().__init__("Fcoin", native_symbol)

  def snapshot(self, bids: list, asks: list):
    self._ask_price_map.clear()
    self._bid_price_map.clear()

    assert len(bids) % 2 == 0
    assert len(asks) % 2 == 0
    for price, qty in zip(*[iter(bids)] * 2):
      price = float(price)
      qty = float(qty)
      self._insert_bid(price, qty, insert_only=True)
    for price, qty in zip(*[iter(asks)] * 2):
      price = float(price)
      qty = float(qty)
      self._insert_ask(price, qty, insert_only=True)

  def _insert_bid(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._bid_price_map
    self._bid_price_map[price] = entry

  def _insert_ask(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._ask_price_map
    self._ask_price_map[price] = entry

  def _delete_bid(self, price):
    del self._bid_price_map[price]

  def _delete_ask(self, price):
    del self._ask_price_map[price]
